<?php

namespace app\controller\api\v1\recovery;


use app\Core\alicode\AliSms;
use app\model\user\User;
use app\model\user\UserBill;
use app\model\user\UserShareInviteLog;
use app\model\v1\recovery\ConfigAbout;
use app\model\v1\recovery\ConfigActivity;
use app\model\v1\recovery\RecoveryFeedBack;
use app\model\v1\recovery\RecoveryFeedBackItem;
use app\model\v1\recovery\RecoveryProductQuote;
use app\model\v1\recovery\RecoveryProductShop;
use app\model\v1\recovery\RecoveryUserRelation;
use app\model\v1\recovery\RecoveryUserSearchHistory;
use app\model\v1\recruit\RecruitJob;
use app\Request;
use app\model\v1\recovery\RecoveryProduct;
use app\model\v1\recovery\RecoveryProductCategory;
use app\services\message\service\StoreServiceServices;
use app\services\order\store\PushMsgServices;
use app\services\store\LoginServices;
use app\services\user\UserServices;
use app\services\v1\recovery\RecoveryProductServices;
use app\validate\api\recovery\createRecoveryValidate;
use app\validate\api\recovery\plateValidate;
use app\validate\api\recovery\quoteValidate;
use app\validate\api\recovery\regAuthValidate;
use app\Core\umeng\Umeng;
use crmeb\exceptions\ApiException;
use think\facade\Db;
use think\facade\Log;

class RecoveryPlate
{

    protected $services;
    protected $storeServices;
    protected $model;
    protected $userinfo = [];


    public function __construct(RecoveryProductServices $services, StoreServiceServices $storeServices)
    {
        $this->services = $services;
        $this->storeServices = $storeServices;
        $this->model = new RecoveryProduct();
    }


    const UMENG_APPKEY = '6706575061c3b13bde9e0d7a';
    const UMENG_APPSECRET = 'jdqilvvvrs2sann1rjrhnah39b6xxtsl';

    const UMENG_VERIFY_APPKEY = '204737075';
    const UMENG_VERIFY_APPSECRET = 'M8NetK5hYkFbzNcdhFqiawyi6X1yv1oM';
    const UMENG_VERIFY_APPCODE = '498c6f2040f241a6b01de3757ee5fc52';

    const UMENG_VERIFY_DISTRIBUT_APPKEY = '6706575061c3b13bde9e0d7a';
    const UMENG_VERIFY_DISTRIBUT_SECRETKEY = 'MDrscCkLs135R+4CccnICo8bJX9qRIADkQ8QMI+OvEb8iMLqFk7kP61YQ/Pn9YwiOJBg+HAaGgKw7jd4KfMdZvLq6wozv3yuGHR602YWzdvuRjjhciS5dBcNad+nrw8JPK8B6DoREG8wAu0xGJSHmTQYS+2r96ngwCV8YLfKqlTKo6qaNl1jLoErJ3VjZeAnBKmfbDmD1FUq+6zkQaV6zHObvHty/xxirih15LzB7TgtCsVn/xj+MCm4xa93pNR+CrZGIIeGKKfkniZ9dEjZLT9qUJq6WUeJVP5kRu8BFKe25u4x4vMrww==';



    public function code_sms()
    {
        //需要发送的用户数组
        $users=[
            [
                'mobile' => '18600532697',
                'name' => '姓名'
            ]
        ];

        foreach ($users as $user){
            //手机
            $mobile = $user['mobile'];
            //姓名
            $name = $user['name'];

            //短信参数
            $params = [
                'name' => $name,//姓名
            ];

            //发送短信
            $this->sendSms($mobile,'SMS_288110779',$params);
        }
    }
    //发送短信
    private function sendSms($mobile,$smsCode,$params=''){
        //手机号码
        $phone = trim($mobile);

        $data = [
            'templateCode' => $smsCode,//短信模板编号
            'phone' => $phone,//手机号码
            //短信参数
            'params' => $params
        ];

        //调用阿里云短信发送方法
        $result = AliSms::main($data);
        var_dump($result);
    }


    /**
     * 友盟系统推送
     * @param Request $request
     * @return \think\Response
     */
    public function umengPushMsg(Request $request)
    {
        try {
            $device_token = $request->post('device_token', '');
            $str = $request->post('str', '');
            $umeng = new Umeng(self::UMENG_APPKEY, self::UMENG_APPSECRET);
            //$umeng->sendAndroidBroadcast();  //安卓  广播
            $res = $umeng->sendAndroidUnicast($device_token, $str);  //安卓  单播
            //$umeng->sendAndroidFilecast();  //安卓  文件播

            if ($res) return app('json')->success('推送成功');
            return app('json')->fail('推送失败');
        }catch (\Throwable $e){
            return app('json')->fail($e->getMessage());
        }
    }



    /**
     * 首页 - top区域 - 搜索
     * @param Request $request
     * @return \think\Response
     */
    public function getTopSearchList(Request $request)
    {
        /*
        $umeng = new Umeng("6706575061c3b13bde9e0d7a", "jdqilvvvrs2sann1rjrhnah39b6xxtsl");
        $umeng->sendAndroidBroadcast();  //安卓  广播
        $umeng->sendAndroidUnicast();  //安卓  单播
        $umeng->sendAndroidFilecast();  //安卓  文件播
        */

        [$word, $type] = $request->getMore([
            ['word', ''],
            ['type', 1],
        ], true);

        if (!empty($word) && $request->uid()) {
            if (!RecoveryUserSearchHistory::where(['uid' => $request->uid(), 'keyword' => $word,'topic' => '4'])->count()) {
                RecoveryUserSearchHistory::create([
                    'uid' => $request->uid(),
                    'topic' => 4,
                    'keyword' => $word,
                ]);
            }
        }

        $list = $this->services->getTopSearchList($request->uid() ?? 0, '*', (string)$word, (int)$type);
        return app('json')->success($list);
    }


    /**
     * 首页 - 获取中部区域 - 分类列表
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCategory(Request $request)
    {
        $data = RecoveryProductCategory::field('id,cate_name,pid as parent_id,sort,pic')->whereNull("delete_time")->select();
        $tree = $this->buildTree($data);

        return app('json')->success($tree);
    }



    public function buildTree($data, $parentId = 0) {
        $tree = array();
        foreach ($data as $item) {
            if ($item['parent_id'] == $parentId) {
                $children = $this->buildTree($data, $item['id']);
                if (!empty($children)) {
                    $item['children'] = $children;
                }
                $tree[] = $item;
            }
        }
        return $tree;
    }


    /**
     * 首页 - 闲置好物商品列表
     * @param Request $request
     * @return \think\Response
     */
    public function getPeripProductList(Request $request)
    {
        $params = $request->param();
        $params["page"] = $params['page'] ?? 1;
        $params["limit"] = $params['limit'] ?? 10;

        //根据商品的浏览量，价格便宜获取商品列表
        $data = RecoveryProduct::getPeripProductList($params);

        return app('json')->success($data);
    }


    /**
     * 首页 - 卡类商品列表
     * @param Request $request
     * @return \think\Response
     */
    public function getCardProductList(Request $request)
    {
        $params = $request->param();
        $params["page"] = $params['page'] ?? 1;
        $params["limit"] = $params['limit'] ?? 10;

        //根据商品的浏览量，价格便宜获取商品列表
        $data = RecoveryProduct::getCardProductList($params);

        return app('json')->success($data);
    }


    /**
     * 首页 - 自由市场商品列表
     * @param Request $request
     * @return \think\Response
     */
    public function getFreeMarkList(Request $request)
    {
        $params = $request->param();
        $params["limit"] = $params['limit'] ?? 10;
        $params["page"] = $params['page'] ?? 1;

        //根据自由市场的分类id获取自由市场的商品列表
        $data = RecoveryProduct::getFreeMarkList($params);

        return app('json')->success($data);
    }


    /**
     * 首页 - 店铺闲置商品列表
     * @param Request $request
     * @return \think\Response
     */
    public function getFreeIdleList(Request $request)
    {
        $params = $request->param();
        $params["limit"] = $params['limit'] ?? 10;
        $params["page"] = $params['page'] ?? 1;

        $params["user_id"] = $request->uid();
        $data = RecoveryProduct::getFreeIdleList($params);

        return app('json')->success($data);
    }


    /**
     * 获取用户店铺
     * @param Request $request
     * @return \think\Response
     */
    public function getUserShop(Request $request)
    {
        $param = $request->param();

        $param['user_id'] = $request->uid();
        try {
            $data = RecoveryProduct::getUserShop($param);

            return app('json')->success($data);
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    public function getUserShopNot(Request $request)
    {
        $param = $request->param();

        $param['user_id'] = $request->uid();
        try {
            $data = RecoveryProduct::getUserShopNot($param);

            return app('json')->success($data);
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }



    /**
     * 获取用户最新店铺信息
     * @param Request $request
     * @return \think\Response
     */
    public function getUserShopInfo(Request $request)
    {
        $param = $request->param();

        $param['user_id'] = $request->uid();
        try {
            $detail = RecoveryProduct::getUserShopInfo($param);

            return app('json')->success($detail);
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }




    /**
     * 首页 - 根据店铺闲置分类 - 获取店铺列表
     * @param Request $request
     * @return \think\Response
     */
    public function getCategoryShopList(Request $request)
    {
        $params = $request->param();
        if(empty($params["category_id"])) return app('json')->fail('category_id不能为空');
        $params["limit"] = $params['limit'] ?? 10;
        $params["page"] = $params['page'] ?? 1;

        $params["user_id"] = $request->uid();
        $data = RecoveryProductShop::getCategoryShopList($params);

        return app('json')->success($data);
    }


    /**
     * 首页 - 店铺闲置 - 店铺详情
     * @param Request $request
     * @return \think\Response
     */
    public function getProductShopDetail(Request $request)
    {
        $id = $request->get('id', 0);
        if(empty($id))  return app('json')->fail('id店铺id不能为空');

        $param = $request->param();
        try {
            //根据店铺的id获取店铺的详情信息
            $item = RecoveryProductShop::detail($id, $param);

            return app('json')->success($item);
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 个人中心 - 新增回收/搬家入驻类型
     * @param Request $request
     * @return \think\Response
     */
    public function createRecoveryShopType(Request $request)
    {
        $param = $request->post();
        if(empty($param["recovery_type"])) return app('json')->fail('请选择回收类型！');
        if(empty($param["type"])) return app('json')->fail('type不能为空');

        $param['user_id'] = $request->uid();
        try {
            //新增回收入驻的类型和搬家入驻的类型
            $res = RecoveryProduct::createRecoveryShopType($param);
            if($res > 0){
                return app('json')->success('success');
            }

            return app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 我卖出的 - 待取货详情
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getMySaleDetail(Request $request)
    {
        $params = $request->param();
        if(empty($params["quote_id"])) return app('json')->fail('quote_id不能为空');

        //根据用户id从用户报价中获取一条商品的报价信息
        $params["user_id"] = $request->uid();
        $data = RecoveryProduct::getMySaleDetail($params);

        return app('json')->success($data->toArray());
    }


    /**
     * 我卖出的 - 全部商品列表
     * @param Request $request
     * @return \think\Response
     */
    public function getMySaleList(Request $request)
    {
        $params = $request->param();
        $params["limit"] = $params['limit'] ?? 10;
        $params["page"] = $params['page'] ?? 1;

        $params["user_id"] = $request->uid();

        //获取我卖出的，全部商品列表
        $data = RecoveryProduct::getMySaleList($params);

        return app('json')->success($data);
    }


    /**
     * 我卖出的 - 列表同意按钮
     * @param Request $request
     * @return \think\Response
     */
    public function enableQuote(Request $request)
    {
        $param = $request->postMore([
            ['quote_id', ''],
            ['product_id', ''],
            ['is_agree', ''],
        ]);
        validate(quoteValidate::class)->check($param);

        $param['user_id'] = $request->uid();
        try {
            $res = RecoveryProductQuote::enableQuote($param);
            if($res){
                return app('json')->success('success');
            }

            return app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 个人中心 - 获取数量
     * @param Request $request
     * @return \think\Response
     * @throws \think\Exception
     */
    public function getListCount(Request $request)
    {
        $params = $request->param();

        $params["user_id"] = $request->uid();
        $data = RecoveryProduct::getListCount($params);

        return app('json')->success($data);
    }


    /**
     * 实名认证提交
     * @param Request $request
     * @return \think\Response
     */
    public function regAuthentication(Request $request)
    {
        $param = $request->postMore([
            ['valid_type', ''],
            ['name', ''],
            ['idcard', ''],
            ['img', ''],
        ]);
        validate(regAuthValidate::class)->check($param);

        $param['user_id'] = $request->uid();
        try {
            $res = RecoveryProduct::addRegAuthent($param);
            if($res > 0){
                return app('json')->success('success');
            }
            return app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 回收/搬家入驻
     * @param Request $request
     * @return \think\Response
     */
    public function createRecovery(Request $request)
    {
        $param = $request->postMore([
            ['reg_type', ''],
            ['city_id', ''],
            ['area_id', ''],
            ['recovery_type', ''],
            ['type', ''],
        ]);
        validate(createRecoveryValidate::class)->check($param);

        $param['user_id'] = $request->uid();
        try {
            $res = RecoveryProduct::createRecovery($param);
            if($res > 0){
                return app('json')->success('success');
            }

            return app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 个人中心 - 我的收藏商品列表
     * @param Request $request
     * @return \think\Response
     */
    public function collectList(Request $request)
    {
        try {
            $param = $request->param();
            $param["page"] = $param["page"] ?? 1;
            $param["limit"] = $param["limit"] ?? 10;

            $param['uid'] = $request->uid();
            $data = RecoveryUserRelation::getCollectList($param);

            return app('json')->success($data);
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 我发布的 - 全部商品
     * @param Request $request
     * @return \think\Response
     */
    public function getMyPublishList(Request $request)
    {
        //接收用户传参的所有参数
        $params = $request->param();
        $params["limit"] = $params['limit'] ?? 10;
        $params["page"] = $params['page'] ?? 1;

        //获取我发布的 全部商品列表
        $params["user_id"] = $request->uid();
        $data = RecoveryProduct::getMyPublishList($params);

        return app('json')->success($data);
    }


    /**
     * 我的发布 - 商品编辑
     * @param Request $request
     * @return \think\Response
     */
    public function updatePublish(Request $request)
    {
        //校验用户传入的参数
        $param = $request->post();
        validate(plateValidate::class)->check($param);

        $pattern = '/^\d+(?:\.\d{1,2})?$/';
        if(!preg_match($pattern, $param["price"])) return app('json')->fail('价格必须为数字，且小数点不能超过两位！');

        $param["images"] = $request->post("images", "");
        $param['user_id'] = $request->uid();
        try {
            //商品编辑
            $res = RecoveryProduct::updateProduct($param);
            if($res >= 0){
                return app('json')->success('success');
            }
            return app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 我的发布 - 商品下架
     * @param Request $request
     * @return \think\Response
     */
    public function enablePublish(Request $request)
    {
        $param = $request->post();
        if(empty($param["id"])) return app('json')->fail('id必填');
        if(empty($param["on_sale"])) return app('json')->fail('on_sale下架状态必填');

        $param['user_id'] = $request->uid();
        try {
            $res = RecoveryProduct::enablePublish($param);
            if($res >= 0){
                return app('json')->success('success');
            }

            return app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 我的发布 - 店铺下架
     * @param Request $request
     * @return \think\Response
     */
    public function enablePublishShop(Request $request)
    {
        $param = $request->post();
        if(empty($param["id"])) return app('json')->fail('店铺id必填');
        if(empty($param["on_sale"])) return app('json')->fail('on_sale下架状态必填');

        $param['user_id'] = $request->uid();
        try {
            $res = RecoveryProductShop::enablePublishShop($param);
            if($res >= 0){
                return app('json')->success('success');
            }

            return app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }




    /**
     * 我的发布 - 商品删除
     * @param Request $request
     * @return \think\Response
     */
    public function delPublish(Request $request)
    {
        $param = $request->post();
        if(empty($param["id"])) return app('json')->fail('id必填');

        try {
            $res = RecoveryProduct::delPublish($param);
            if($res >= 0){
                return app('json')->success('success');
            }
            return app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 我的发布 - 店铺删除
     * @param Request $request
     * @return \think\Response
     */
    public function delPublishShop(Request $request)
    {
        $param = $request->post();
        if(empty($param["id"])) return app('json')->fail('id必填');

        try {
            $res = RecoveryProductShop::delPublishShop($param);
            if($res >= 0){
                return app('json')->success('success');
            }
            return app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }



    /**
     * 我买到的 - 全部商品列表
     * @param Request $request
     * @return \think\Response
     */
    public function getBuyList(Request $request)
    {
        $params = $request->param();
        $params["limit"] = $params['limit'] ?? 10;
        $params["page"] = $params['page'] ?? 1;

        $params["user_id"] = $request->uid();

        $data = RecoveryProduct::getBuyList($params);

        return app('json')->success($data);
    }


    /**
     * 我买到的 - 确认收货
     * @param Request $request
     * @return \think\Response
     */
    public function enableBuyQuote(Request $request)
    {
        $param = $request->post();
        if(empty($param["quote_id"])) return app('json')->fail('quote_id必填');
        if(empty($param["product_id"])) return app('json')->fail('product_id必填');

        $param['user_id'] = $request->uid();
        try {
            $res = RecoveryProductQuote::enableBuyQuote($param);
            if($res["status"]){
                return app('json')->success('success');
            }

            return app('json')->fail($res['msg'] ?? 'fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 个人中心 - 常见问题 - 获取分类类型
     * @param Request $request
     * @return \think\Response
     */
    public function getFeedBackData(Request $request)
    {
        $params = $request->param();

        $data = RecoveryFeedBack::getFeedBackData($params);

        return app('json')->success($data);
    }


    /**
     * 个人中心 - 获取问题反馈分类
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getQuestionCate(Request $request)
    {
        $params = $request->param();
        if(empty($params["type"])) return app('json')->fail('type参数不能为空');

        $params["user_id"] = $request->uid();
        $data = RecoveryFeedBack::getQuestionCate($params);

        return app('json')->success($data);
    }


    /**
     * 个人中心 - 宝贝详情页面 - 交易须知
     * @param Request $request
     * @return \think\Response
     */
    public function getFeedbackItemType(Request $request)
    {
        $params = $request->param();

        $detail = RecoveryFeedBack::getFeedbackItemType($params);

        return app('json')->success($detail ? $detail->toArray() : []);
    }





    /**
     * 个人中心 - 问题反馈提交
     * @param Request $request
     * @return void
     */
    public function createQuestion(Request $request)
    {
        $param = $request->post();
        if(empty($param["cate_id"])) return app('json')->fail('请选择问题类型！');
        if(empty($param["desc"])) return app('json')->fail('请填写问题描述！');

        $param['user_id'] = $request->uid();
        try {
            $res = RecoveryFeedBack::createQuestion($param);
            if($res > 0){
                return app('json')->success('success');
            }

            return app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 我买到的 - 用户取消交易
     * @param Request $request
     * @return \think\Response
     */
    public function cancelBuyQuote(Request $request)
    {
        $param = $request->post();
        if(empty($param["quote_id"])) return app('json')->fail('quote_id参数不能为空');
        if(empty($param["product_id"])) return app('json')->fail('product_id参数不能为空');

        $param['user_id'] = $request->uid();
        try {
            $res = RecoveryProductQuote::cancelBuyQuote($param);
            if($res["status"]){
                return app('json')->success('success');
            }

            return app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 获取用户VIP剩余天数
     * @param Request $request
     * @return \think\Response
     */
    public function getVipMainDay(Request $request)
    {
        $params = $request->param();

        $params['user_id'] = $request->uid();
        $res = User::getVipMainDay($params);

        return app('json')->success($res);
    }


    /**
     * 我买到的 - 删除订单
     * @param Request $request
     * @return \think\Response
     */
    public function delBuyQuote(Request $request)
    {
        $param = $request->post();
        if(empty($param["quote_id"])) return app('json')->fail('quote_id参数不能为空');
        if(empty($param["product_id"])) return app('json')->fail('product_id参数不能为空');
        if(empty($param["is_buy"])) return app('json')->fail('is_buy参数不能为空');

        $param['user_id'] = $request->uid();
        try {
            $res = RecoveryProductQuote::delBuyQuote($param);
            if($res >= 0){
                return app('json')->success('success');
            }

            return app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 我买到的 - 待取货详情
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getBuyDetail(Request $request)
    {
        $params = $request->param();
        if(empty($params["quote_id"])) return app('json')->fail('quote_id不能为空');

        $params["user_id"] = $request->uid();
        $detail = RecoveryProduct::getBuyDetail($params);

        return app('json')->success($detail ? $detail->toArray() : []);
    }


    /**
     * 个人中心 - 常见问题 - 问题详情页面
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getFeedBackItem(Request $request)
    {
        $params = $request->param();
        if(empty($params["f_id"])) return app('json')->fail('f_id不能为空');

        $params["user_id"] = $request->uid();
        $data = RecoveryFeedBackItem::getFeedBackItem($params);

        return app('json')->success($data);
    }



    /**
     * 关于我们 - 检查更新
     * @param Request $request
     * @return \think\Response
     */
    public function checkUpdateVersion(Request $request)
    {
        $params = $request->param();
        if(empty($params["version"])) return app('json')->fail('version版本号不能为空');
        if(empty($params["app_type"])) return app('json')->fail('app_type不能为空');

        $data = ConfigAbout::checkUpdateVersion($params);

        return app('json')->success($data ? $data->toArray() : []);
    }


    /**
     * 关于我们 - 获取详情
     * @param Request $request
     * @return \think\Response
     */
    public function getAboutInfo(Request $request)
    {

        $params = $request->param();
        if(empty($params["type"])) return app('json')->fail('type不能为空');
        if(empty($params["app_type"])) return app('json')->fail('app_type不能为空');

        if(!in_array($params["type"], [1,2,3,4,5])) return app('json')->fail('参数错误');

        $data = ConfigAbout::getAboutInfo($params);

        return app('json')->success($data ? $data->toArray() : []);
    }


    /**
     * 智能认证 - 签名
     * @param Request $request
     * @return void
     */
    public function oneclick_login(Request $request)
    {
        try {
            $mobile_token = $request->post('mobile_token');
            $host = "https://verify5.market.alicloudapi.com";
            $path = "/api/v1/mobile/info";
            $method = "POST";
            $accept = "application/json";
            $content_type = "application/json; charset=UTF-8";
            $appKey = self::UMENG_VERIFY_APPKEY; //阿里云市场购买应用的appKey
            $appSecret = self::UMENG_VERIFY_APPSECRET; //阿里云市场购买应用的appSecret
            $um_appkey = self::UMENG_VERIFY_DISTRIBUT_APPKEY; //友盟的appkey

            $header["Accept"] = $accept;
            $header["Content-Type"] = $content_type;
            $header["X-Ca-Version"] = "1";
            $header["X-Ca-Signature-Headers"] = "X-Ca-Key,X-Ca-Nonce,X-Ca-Stage,X-Ca-Timestamp,X-Ca-Version";
            $header["X-Ca-Stage"] = "RELEASE";
            $header["X-Ca-Key"] = $appKey;
            $header["X-Ca-Timestamp"] = strval(time() * 1000);
            mt_srand((double)microtime() * 10000);
            $uuid = strtoupper(md5(uniqid(rand(), true)));
            $header["X-Ca-Nonce"] = strval($uuid);
            //Headers
            $headers = "X-Ca-Key:" . $header["X-Ca-Key"] . "\n";
            $headers .= "X-Ca-Nonce:" . $header["X-Ca-Nonce"] . "\n";
            $headers .= "X-Ca-Stage:" . $header["X-Ca-Stage"] . "\n";
            $headers .= "X-Ca-Timestamp:" . $header["X-Ca-Timestamp"] . "\n";
            $headers .= "X-Ca-Version:" . $header["X-Ca-Version"] . "\n";
            //Url
            $url = $path . "?appkey=" . $um_appkey; //appkey为用户在友盟注册的应用分配的appKey,token和phoneNumber是app传过来的值
            //sign
            $str_sign = $method . "\n";
            $str_sign .= $accept . "\n";
            $str_sign .= "\n";
            $str_sign .= $content_type . "\n";
            $str_sign .= "\n";
            $str_sign .= $headers;
            $str_sign .= $url;
            $sign = base64_encode(hash_hmac('sha256', $str_sign, $appSecret, true)); //secret为APP的密钥
            $header['X-Ca-Signature'] = $sign;
            $post_data['token'] = $mobile_token;
            //curl
            $curl_url = $host . $path . "?appkey=" . $um_appkey; //appkey为用户在友盟注册的应用分配的appKey
            $headerArray = array();
            foreach ($header as $k => $v) {
                array_push($headerArray, $k . ":" . $v);
            }
            $result = $this->CURL_POST($method, $curl_url, $headerArray, $post_data);
            Log::info('oneclick-return: '. $result);
            //var_dump($result);


            $pos = strpos($result, "{");
            $extract = substr($result, $pos, -1) . '}';
            $result = json_decode($extract, true);
            if(isset($result['success']) && $result['success']){
                $mobile = $result['data']['mobile'];
                $user_info = User::where('phone', $mobile)->whereNull("delete_time")->order('uid','asc')->limit(1)->find() ?? [];

                if(!empty($user_info)){
                    $user_info = $user_info->toArray();
					User::where('uid', $user_info['uid'])->update(['client_type'=>$request->header('Client-type'??'')]);
                    $this->addUserShareInvite($user_info);
                }else{
                    $user_info = [
                        "account" => $mobile,
                        "pwd" => md5(User::INIT_PWD),
                        "phone" => $mobile,
                        "nickname" => str_replace(substr($mobile,3,4), "****",$mobile),
                        "user_type" => "app",
                        "avatar" => sys_config('h5_avatar'),
                        "add_time" => time(),
                        "add_ip" => $request->ip(),
                        "integral" => 0,
                        "client_type" =>$request->header('Client-type'??'')
	                ,
//                        "integral" => User::NEW_REG_INTEGRAL,
                    ];
                    $new_uid = Db::name("user")->insertGetId($user_info);
                    $user_info["uid"] = $new_uid;


                    if (!$new_uid) {
                        throw new ValidateException('用户登录失败,无法生成新用户,请稍后再试!');
                    }
                    /** @var UserServices $userServices */
                    $userServices = app()->make(UserServices::class);
                    $userServices->incField($user_info['uid'], 'integral', User::NEW_REGISTER_INTEGRAL);
                    $add = [
                        'uid' => $user_info['uid'],
                        'pm' => 1,
                        'title' => '新用户注册赠送积分',
                        'category' => 'integral',
                        'type' => 'share_news',
                        'number' => User::NEW_REGISTER_INTEGRAL,
                        'balance' => User::NEW_REGISTER_INTEGRAL,
                        'mark' => '新用户注册赠送'.User::NEW_REGISTER_INTEGRAL.'积分',
                        'add_time' => time(),
                    ];
                    UserBill::create($add);

                    /** @var PushMsgServices  $pushMsgServices */
                    $pushMsgServices = app()->make(PushMsgServices::class);
                    //友盟系统消息
                    $pushMsgServices->umengPushMsg((int)$user_info['uid'], '', 10, (string)User::NEW_REGISTER_INTEGRAL);
                    ////return app('json')->fail("未获取到此手机号{$mobile}的用户信息.");
                }

                $uid = (int)$user_info['uid'];
                $services = app()->make(LoginServices::class);
                $token = $services->createToken($uid, 'api', $user_info['pwd']);
                event('user.login', [$uid, app('request')->ip()]);
                $user_info['bear_token'] = $token['token'] ?? '';
                $user_info['bear_token_expires_time'] = $token['params']['exp'] ?? '';
                $result['data']['userinfo'] = $user_info;
            }
            return app('json')->success($result);
        }catch (\Throwable $e){
            return app('json')->fail($e->getMessage());
        }
    }



    public function addUserShareInvite($user_info = [])
    {
        //----------------------------分享者人数、积分更新--------------------------
        //注册送积分，用户从app登录后
        $share_pid = 0;
        $integral = 0;
        $share_ids = [];
        $share_id_count = 0;
        $uid = 0;
        if(!empty($user_info['pid_share_code']) &&  ($user_info['is_app_login']==2) ){
            $uid = $user_info['uid'];
            if(!empty($user_info['pid_share_code']) &&  ($user_info['is_app_login']==2) ) {
                $code_find = User::where(['share_code' => $user_info['pid_share_code']])->find();
                if (!empty($code_find)) {
                    $share_pid = $code_find->uid; //分享者id
                    $integral = $code_find->integral ?? 0;
                    $share_id_count = $code_find->subordinate_count ?? 0; //ids数量
                    if (!empty($code_find->subordinate)) $share_ids = explode(',', $code_find->subordinate ?? ''); //ids
                }
            }
        }

        if(!empty($share_pid)){
            array_push($share_ids, $uid);
            $subordinate = implode(',', $share_ids);
            $update = [
                'subordinate' => $subordinate,
                'integral' => $integral+User::SHARE_NEW_INTEGRAL,
                'subordinate_count' => $share_id_count+1,
                'is_app_login' => 1,
            ];
            User::where("uid", $share_pid)->update($update);

            //分享邀请记录添加
            UserShareInviteLog::addUserShareInvateLog($share_pid,1,User::SHARE_NEW_INTEGRAL, $uid);
            Log::info('one_clicklogin_log:'.'share_pid:'.$share_pid.' uid:'.$uid);

            //友盟系统消息
//	        /** @var PushMsgServices $pushMsgServices */
//            $pushMsgServices = app()->make(PushMsgServices::class);
//            $pushMsgServices->umengPushMsg($share_pid, '', 5, User::SHARE_NEW_INTEGRAL);

            $add = [
                'uid' => $share_pid,
                'pm' => 1,
                'title' => '分享新用户注册赠送积分',
                'category' => 'integral',
                'type' => 'share_new',
                'number' => User::SHARE_NEW_INTEGRAL,
                'balance' => $integral+User::SHARE_NEW_INTEGRAL,
                'mark' => '分享新用户注册赠送'.User::SHARE_NEW_INTEGRAL.'积分',
                'add_time' => time(),
            ];
            UserBill::create($add);
        }
        //--------------------------------------------------------------------
    }


    /**
     * 智能认证 - 本机号码认证
     * @param Request $request
     * @return void
     */
    public function phone_verify(Request $request)
    {
        try {
            $mobile_token = $request->post('mobile_token');
            $mobile = $request->post('mobile');
            $host = "https://verify5.market.alicloudapi.com";
            $path = "/api/v1/mobile/verify";
            $method = "POST";
            $accept = "application/json";
            $content_type = "application/json; charset=UTF-8";
            $appKey = self::UMENG_VERIFY_APPKEY; //阿里云市场购买应用的appKey
            $appSecret = self::UMENG_VERIFY_APPSECRET; //阿里云市场购买应用的appSecret
            $um_appkey = self::UMENG_VERIFY_DISTRIBUT_APPKEY; //友盟的appkey

            $header["Accept"] = $accept;
            $header["Content-Type"] = $content_type;
            $header["X-Ca-Version"] = "1";
            $header["X-Ca-Signature-Headers"] = "X-Ca-Key,X-Ca-Nonce,X-Ca-Stage,X-Ca-Timestamp,X-Ca-Version";
            $header["X-Ca-Stage"] = "RELEASE";
            $header["X-Ca-Key"] = $appKey;
            $header["X-Ca-Timestamp"] = strval(time() * 1000);
            mt_srand((double)microtime() * 10000);
            $uuid = strtoupper(md5(uniqid(rand(), true)));
            $header["X-Ca-Nonce"] = strval($uuid);
            //Headers
            $headers = "X-Ca-Key:" . $header["X-Ca-Key"] . "\n";
            $headers .= "X-Ca-Nonce:" . $header["X-Ca-Nonce"] . "\n";
            $headers .= "X-Ca-Stage:" . $header["X-Ca-Stage"] . "\n";
            $headers .= "X-Ca-Timestamp:" . $header["X-Ca-Timestamp"] . "\n";
            $headers .= "X-Ca-Version:" . $header["X-Ca-Version"] . "\n";
            //Url
            $url = $path . "?appkey=" . $um_appkey; //appkey为用户在友盟注册的应用分配的appKey,token和phoneNumber是app传过来的值
            //sign
            $str_sign = $method . "\n";
            $str_sign .= $accept . "\n";
            $str_sign .= "\n";
            $str_sign .= $content_type . "\n";
            $str_sign .= "\n";
            $str_sign .= $headers;
            $str_sign .= $url;
            $sign = base64_encode(hash_hmac('sha256', $str_sign, $appSecret, true)); //secret为APP的密钥
            $header['X-Ca-Signature'] = $sign;
            $post_data['token'] = $mobile_token;
            $post_data['phoneNumber'] = $mobile;
            //curl
            $curl_url = $host . $path . "?appkey=" . $um_appkey; //appkey为用户在友盟注册的应用分配的appKey
            $headerArray = array();
            foreach ($header as $k => $v) {
                array_push($headerArray, $k . ":" . $v);
            }
            $result = $this->CURL_POST($method, $curl_url, $headerArray, $post_data);
            //var_dump($result);

            $pos = strpos($result, "{");
            $extract = substr($result, $pos, -1) . '}';
            $result = json_decode($extract, true);
            /*if(isset($result['success']) && $result['success']){
                $mobile = $result['data']['mobile'];
                $user_info = User::where('phone', $mobile)->order('uid','asc')->limit(1)->find() ?? [];
                if(!empty($user_info)) $user_info = $user_info->toArray();
                $result['data']['userinfo'] = $user_info;
            } */
            return app('json')->success($result);
        }catch (\Throwable $e){
            return app('json')->fail($e->getMessage());
        }
    }



    public function CURL_POST(string $method, string $curl_url, array $headerArray, array $post_data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $curl_url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post_data));
        $result = curl_exec($curl);
        return $result;
    }


    /**
     * 创建客服账号
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function createService(Request $request)
    {
        $data = $request->postMore([
            ['image', ''],
            ['uid', 0],
            ['avatar', ''],
            ['customer', ''],
            ['notify', ''],
            ['phone', ''],
            ['account', ''],
            ['password', ''],
            ['true_password', ''],
            ['phone', ''],
            ['nickname', ''],
            ['status', 1],
            ['account_status', 1],
        ]);
        if ($data['image'] == '') return app('json')->fail('请选择用户');
        $data['uid'] = $data['image']['uid'];

        $userService = app()->make(UserServices::class);
        $userInfo = $userService->get($data['uid']);
        if ($data['phone'] == '') {
            if (!$userInfo['phone']) {
                throw new ApiException('该用户没有绑定手机号，请手动填写');
            } else {
                $data['phone'] = $userInfo['phone'];
            }
        } else {
            if (!check_phone($data['phone'])) throw new ApiException('请输入正确的手机号');
        }
        if ($data['nickname'] == '') $data['nickname'] = $userInfo['nickname'];
        $data['avatar'] = $data['image']['image'];
        if ($this->storeServices->count(['uid' => $data['uid']])) {
            return app('json')->fail('客服已存在!');
        }
        unset($data['image']);
        $data['add_time'] = time();
        if (!$data['account']) return app('json')->fail('请输入账号');

        if (!preg_match('/^[a-zA-Z0-9]{4,30}$/', $data['account'])) return app('json')->fail('账号必须为数字或者字母的组合4-30位');
        if (!$data['password']) return app('json')->fail('请输入密码');
        if (!preg_match('/^[0-9a-z_$]{6,20}$/i', $data['password'])) return app('json')->fail('密码必须为数字或者字母的组合6-20位');

        if ($this->storeServices->count(['phone' => $data['phone']])) return app('json')->fail('该手机号的客服已存在!');
        if ($this->storeServices->count(['account' => $data['account']])) return app('json')->fail('该客服账号已存在!');

        $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        $res = $this->storeServices->save($data);
        if ($res) {
            return app('json')->success('客服添加成功');
        } else {
            return app('json')->fail('客服添加失败，请稍后再试');
        }
    }



    /**
     * 用户邀请记录列表
     * @param Request $request
     * @return \think\Response
     */
    public function getUserShareInviteList(Request $request)
    {
        $params = $request->param();
        $params["limit"] = $params['limit'] ?? 10;
        $params["page"] = $params['page'] ?? 1;

        $params["user_id"] = $request->uid();
        $data = UserShareInviteLog::getUserShareInviteList($params);

        return app('json')->success($data);
    }


    /**
     * 闲置-模糊搜索
     * @param Request $request
     * @return \think\Response
     * @throws \think\Exception
     */
    public function getListLikeData(Request $request)
    {
        $params = $request->param();
        if(empty($params["type"])) return app('json')->fail("type不能为空");

        $params["user_id"] = $request->uid();
        $data = RecoveryProduct::getListLikeData($params);

        return app('json')->success($data);
    }


    /**
     * 超市-模糊搜索
     * @param Request $request
     * @return \think\Response
     * @throws \think\Exception
     */
    public function getProductLikeData(Request $request)
    {
        $params = $request->param();
        // if(empty($params["type"])) return app('json')->fail("type不能为空");

        // $params["user_id"] = $request->uid();
        $data = RecoveryProduct::getProductLikeData($params);

        return app('json')->success($data);
    }




    /**
     * 弹框点击领取新用户送积分
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function actNewUserInte(Request $request)
    {
        $params = $request->param();
        if(empty($params["client_type"])) return app('json')->fail("client_type不能为空");

        $params["user_id"] = $request->uid();

        $user = User::where("uid", $params["user_id"])->find();
        if($user["is_register_inte"] == 1) return app('json')->fail("积分不能重复领取");

        $loginServices = app()->make(\app\services\user\LoginServices::class);
        $res = $loginServices->actNewUserInte($params);

        return app('json')->success('success');
    }




    /**
     * 弹框点击领取新用户送vip
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function actNewUserMember(Request $request)
    {
        $params = $request->param();
        if(empty($params["client_type"])) return app('json')->fail("client_type不能为空");

        $params["user_id"] = $request->uid();

        $user = User::where("uid", $params["user_id"])->find();
        if($user["is_register_member"] == 1) return app('json')->fail("vip不能重复领取");

        $loginServices = app()->make(\app\services\user\LoginServices::class);
        $res = $loginServices->actNewUserMember($params);

        return app('json')->success('success');
    }

    /**
     * 点击取消推送商品
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function act_goods_id(Request $request)
    {
        $params = $request->param();

        $params["user_id"] = $request->uid();

       User::where("uid", $params["user_id"])->update(['is_recommend_goods_id'=>1]);

        return app('json')->success('success');
    }





    /**
     * 获取活动配置
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getConfigActivityToken(Request $request)
    {
        $params = $request->param();
        $params["limit"] = $params['limit'] ?? 10;
        $params["page"] = $params['page'] ?? 1;
        if(empty($params["client_type"])) return app('json')->fail("client_type不能为空");

        $uid = $request->uid();

        $zation = $request->header('Authori-zation') ?? $request->header('authori-zation');
        if(!empty($zation)){
            if(empty($uid)) return app('json')->fail("已传token， 未解析uid.");
        }

        $params["user_id"] = $uid;
        $data = ConfigActivity::getConfigActivity($params);

        return app('json')->success($data);
    }




    public function getConfigActivity(Request $request)
    {
        $params = $request->param();
        $params["limit"] = $params['limit'] ?? 10;
        $params["page"] = $params['page'] ?? 1;
        if(empty($params["client_type"])) return app('json')->fail("client_type不能为空");

        $params["user_id"] = $request->uid();
        $data = ConfigActivity::getConfigActivity($params);

        return app('json')->success($data);
    }




}